package com.wanpinghui.supplier.business.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.business.adapter.CircleListAdapter;
import com.wanpinghui.wphlibrary.model.business.bean.CommentBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicBean;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.util.ArrayList;
import java.util.List;

/***
 * 功能描述:今日新款评论ListView
 * 作者:xiongning
 * 时间:2016/12/21
 * 版本:v1.0
 ***/

public class CircleCommentListView extends LinearLayout {
    private int itemColor;
    private int itemSelectorColor;
    private CommonListener listener;
    private List<CommentBean> mDatas;
    private LayoutInflater layoutInflater ;
    private DynamicBean mDynamicBean;

    public void setListener(CommonListener listener) {
        this.listener = listener;
    }

    public void setDatas(DynamicBean dynamicBean){
        mDynamicBean = dynamicBean;
        mDatas = null;
        if (dynamicBean != null) {
            mDynamicBean = dynamicBean;
            mDatas = dynamicBean.getReplyList();
        }
        notifyDataSetChanged();
    }

    public List<CommentBean> getDatas(){
        return mDatas;
    }

    public CircleCommentListView(Context context) {
        super(context);
    }

    public CircleCommentListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
    }

    public CircleCommentListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(attrs);
    }

    protected void initAttrs(AttributeSet attrs) {
        TypedArray typedArray = getResources().obtainAttributes(attrs,
                R.styleable.CircleCommentListView);
        try {
            //textview的默认颜色
            itemColor = typedArray.getColor(R.styleable.CircleCommentListView_item_color, getResources().getColor(R.color.color_0f0e10));
            itemSelectorColor = typedArray.getColor(R.styleable.CircleCommentListView_item_selector_color, getResources().getColor(R.color.color_0f0e10));

        }finally {
            typedArray.recycle();
        }
    }

    public void notifyDataSetChanged(){

        removeAllViews();
        if(mDatas == null || mDatas.size() == 0){
            return;
        }
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int i=0; i<mDatas.size(); i++){
            final int index = i;
            View view = getView(index);
            if(view == null){
                throw new NullPointerException("listview item layout is null, please check getView()...");
            }

            addView(view, index, layoutParams);
        }

    }

    private View getView(final int position){

        if(layoutInflater == null){

            layoutInflater = LayoutInflater.from(getContext());

        }

        View convertView = layoutInflater.inflate(R.layout.item_goods_comment, null, false);

        TextView commentTv = (TextView) convertView.findViewById(R.id.tv_comment);

        //final TodayNewGoodsMovementMethod circleMovementMethod = new TodayNewGoodsMovementMethod(itemSelectorColor, itemSelectorColor);

        final CommentBean bean = mDatas.get(position);

        String name = bean.getNickName();

        long id = bean.getId();

        String toReplyName ="";

        if (bean.getReply_to() != 0) {
            toReplyName = bean.getReply_to_nickname();
        }

        SpannableStringBuilder builder = new SpannableStringBuilder();

        builder.append(setClickableSpan(bean, bean.getNickName(), bean.getUser_id()));

        if (!TextUtils.isEmpty(toReplyName) && bean.getUser_id() != bean.getReply_to()) {

            builder.append("回复");

            builder.append(setClickableSpan(bean, toReplyName, bean.getReply_to()));
        }
        SpannableString subjectSpanText = new SpannableString("：");
        subjectSpanText.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(),R.color.colorPrimaryBlue)),0,subjectSpanText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.append(subjectSpanText);
        //转换表情字符
        if (TextUtil.isNotEmpty(bean.getContent())) {
            SpannableString subjectSpanText2 = new SpannableString(bean.getContent());
            subjectSpanText2.setSpan(new ClickableSpan() {
                                         @Override
                                         public void onClick(View widget) {
                                             if (listener != null) {
                                                 listener.onCommont(bean, bean.getUser_id(), bean.getNickName());
                                             }
                                         }

                                         @Override
                                         public void updateDrawState(TextPaint ds) {
                                             ds.setUnderlineText(false);
                                         }
                                     }, 0, subjectSpanText2.length(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.append(subjectSpanText2);
        }
        commentTv.setText(builder);
        commentTv.setMovementMethod(LinkMovementMethod.getInstance());

        //commentTv.setMovementMethod(circleMovementMethod);
//        commentTv.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (circleMovementMethod.isPassToTv()) {
//                    if(onItemClickListener!=null){
//                        onItemClickListener.onItemClick(position);
//                    }
//                }
//            }
//        });
//        commentTv.setOnLongClickListener(new OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                if (circleMovementMethod.isPassToTv()) {
//                    if(onItemLongClickListener!=null){
//                        onItemLongClickListener.onItemLongClick(position);
//                    }
//                    return true;
//                }
//                return false;
//            }
//        });

        return convertView;
    }

    @NonNull
    private SpannableString setClickableSpan(final CommentBean bean, final String textStr, final int toUserId) {
        SpannableString subjectSpanText = new SpannableString(textStr);
        subjectSpanText.setSpan(new ClickableSpan(){
                                    @Override
                                    public void onClick(View widget) {
                                        if (listener != null) {
                                            listener.onUser(toUserId, textStr);
                                        }
                                    }

                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        ds.setUnderlineText(false);
                                    }
                                }, 0, subjectSpanText.length(),
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        subjectSpanText.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(),R.color.colorPrimaryBlue)),0,subjectSpanText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return subjectSpanText;
    }

    public interface CommonListener{
        void onCommont(CommentBean bean, int toUserId, String textStr);
        void onUser(int userId, String userName);
    }
}
